<template>
  <div class="cart">
    <div class="carthead">
      <warp></warp>
    </div>
    <div class="main">
      <div class="top">
        <img src="./assets/logo_writer.png"  alt="">
        <div class="search">
          <input type="text">
          <button @click="searchProducts">搜索</button>
        </div>
      </div>
      <div class="top2">
        <div class="selectProduct">
          <span>全部商品</span><span class="num">{{totalCount}}</span>
        </div>
        <div class="selectAddress">
          <span style="width: 75px">配送至:</span>
          <el-select v-model="address" @change="updateDelivery">
            <el-option v-for="addr in deliveryOptions" :key="addr" :value="addr" :label="addr"/>
          </el-select>
        </div>
      </div>
      <div class="cartList">
        <table>
          <tr class="title">
            <th>
              <input type="checkbox" v-model="selectAll" @change="toggleSelectAll">
              <span style="margin-left: 10px">全选</span>
            </th>
            <th>商品</th>
            <th>单价</th>
            <th>数量</th>
            <th>操作</th>
          </tr>
          <tr>
            <td colspan="5">
              <input type="checkbox" v-model="storeSelected" @change="toggleStoreSelection">
              <span style="margin-left: 10px">京喜自营官方店</span>
            </td>
          </tr>
          <tr v-for="(item, index) in CartList" :key="item.id">
            <td>
              <input type="checkbox" v-model="item.selected" @change="updateSelection">
              <img :src="item.img  || defaultImage" width="100px">
            </td>
            <td class="goodtitle">
              <div class="goodtitle1">
                <span>{{item.title}}</span>
                <p v-if="item.color"> 颜色：{{item.color}}</p>
                <p v-if="item.size"> 尺寸：{{item.size}}</p>
              </div>
            </td>
            <td>￥{{item.price.toFixed(2)}}</td>
            <td>
              <el-input-number v-model="item.quantity" :min="1" :max="99" @change="(val)=>updateQuantity(index, val)"/>
            </td>
            <td>
              <el-button type="danger" plain @click="removeItem(index)">删除</el-button>
            </td>
          </tr>
          <tr>
            <td colspan="5" class="cart-footer">
              <div class="footer-container">
                <div class="action-group">
                  <label class="select-all">
                    <input type="checkbox" v-model="selectAll" @change="toggleSelectAll">
                    <span>全选</span>
                  </label>
                  <button class="text-btn" @click="removeSelected">删除选中的商品</button>
                  <button class="text-btn" @click="clearCart">清理购物车</button>
                </div>
                <div class="checkout-group">
                <span class="summary">已选商品 <em>{{selectedCount}}</em> 件
                </span>
                  <span class="summary">总价 <em>￥{{totalPrice.toFixed(2)}}</em>
                </span>
                  <button class="primary-btn" @click="checkout">去结算</button>
                </div>
              </div>
            </td>
          </tr>
        </table>
      </div>
      <div class="suishougou">
        <div v-for="(item,index) in recommendedProducts" :key="index">
          <div class="tuijianGood">
            <img :src="item.img"  alt="">
            <p>{{item.title}}</p>
            <p>￥{{item.price.toFixed(2)}}</p>
            <button class="primary-btn" @click="addRecommendToCart(item)">加入购物车</button>
          </div>
        </div>
      </div>
    </div>
  </div>
  <end></end>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import {useRoute, useRouter} from 'vue-router'
import Warp from "@/components/warp.vue";
import End from "@/components/end.vue";

const router = useRouter()
const route = useRoute()
const defaultImage = ref('/default-product.png')

// 商品数据
const product = ref({
  ...JSON.parse(route.query.product?.toString()  || '{}'),
  selected: false,
  quantity: 1
})

// 配送选项
const address = ref(product.value.address  || '北院')
const deliveryOptions = ref(['北京','上海','天津','河北','广东','江苏','浙江'])

// 购物车功能
const CartList = ref([product.value])

// 推荐商品
const recommendedProducts = ref([
  {
    id: 'r1',
    title: '益达无糖口香糖混合水果味98g约70粒/瓶',
    price: 10,
    img: require("./assets/yida.png"),
    quantity: 1,
    selected: false
  },
  {
    id: 'r2',
    title: '一天一个小粽子,舒舒服服没烦恼',
    price: 20,
    img: require("./assets/zongzi.png"),
    quantity: 1,
    selected: true
  },
  {
    id: 'r1',
    title: '益达无糖口香糖混合水果味98g约70粒/瓶',
    price: 10,
    img: require("./assets/yida.png"),
    quantity: 1,
    selected: false
  },
  {
    id: 'r1',
    title: '益达无糖口香糖混合水果味98g约70粒/瓶',
    price: 10,
    img: require("./assets/yida.png"),
    quantity: 1,
    selected: false
  },
])

// 计算属性
const totalCount = computed(() =>
    CartList.value.reduce((total,  item) => total + item.quantity,  0)
)

const selectedCount = computed(() =>
    CartList.value.filter(item  => item.selected).reduce((total,  item) => total + item.quantity,  0)
)

const totalPrice = computed(() =>
    CartList.value.filter(item  => item.selected).reduce((total,  item) =>
        total + (item.price  * item.quantity),  0)
)

const selectAll = computed({
  get: () => CartList.value.every(item  => item.selected),
  set: (val) => CartList.value.forEach(item  => item.selected  = val)
})

// 方法实现
const updateQuantity = (index: number, val: number) => {
  CartList.value[index].quantity  = val
}

const removeItem = (index: number) => {
  CartList.value.splice(index,  1)
}

const removeSelected = () => {
  CartList.value  = CartList.value.filter(item  => !item.selected)
}

const clearCart = () => {
  CartList.value  = []
}

const addRecommendToCart = (item: any) => {
  const existing = CartList.value.find(p  => p.id  === item.id)
  if (existing) {
    existing.quantity += 1
  } else {
    CartList.value.push({...item})
  }
}

const checkout=()=>{
  router.push({
    path: '/order.vue',
    query: {
      products: JSON.stringify(CartList.value),
     address: address.value
    }
  })
}

</script>
<style>

.cart{
  display: flex;
  flex-direction: column;
  junal-items: center;
  align-items: center;
  padding: 0 10px;
  margin: 0 auto;
  margin-top: 10px;
}
.carthead{
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
  background: #f5f5f5;
}
.main{
  width: 80%;
  display: block;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
}

.top{
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.top img{
  width: 200px;
}
.search{
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
  margin-bottom: 10px;
  width: 450px;
  height: 30px;
  border : 2px solid #c91623;
}
.search input{
  border: none;
  width: 400px;
  height: 30px;
}
.search button{
  background: #c91623;
  color: #fff;
  border: none;
  width: 50px;
  height: 30px;
}
.num{
  margin-left: 10px;
}
.top2{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.selectAddress{
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
  margin-bottom: 10px;
  width: 450px;
}
.selectProduct {
  display: flex;
  justify-content: center;
  align-items: center;
}
.selectProduct span{
  color: #e2231a ;
  font-size: 20px;
  font-weight: bold;
}
.cartList{
  width: 100%;
}
table{
  width: 100%;
}
td{
  margin-top: 100px;
  margin-bottom: 10px;
  padding: 10px;
}
.title{
  background-color: #fff
}
.title th{
  padding: 5px;
  background: #f5f5f5;

}
.goodtitle{
  width: 100%;
}
.goodtitle1  {
  display: flex;
  justify-content:space-evenly;
}
.cart-footer {
  padding: 12px 16px;
  background: #f8f8f8;
}

.footer-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-width: 100%; /* 强制撑满容器 */
  white-space: nowrap; /* 禁止换行 */
}

/* 操作组样式 */
.action-group {
  display: flex;
  align-items: center;
  gap: 15px; /* 控制按钮间距 */
}

.select-all {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
}

.text-btn {
  border: none;
  background: transparent;
  color: #666;
  cursor: pointer;
  padding: 4px 0;
}

/* 结算组样式 */
.checkout-group {
  display: flex;
  align-items: center;
  gap: 20px;
}

.summary {
  font-size: 14px;
}
.summary em {
  color: #f56c6c;
  font-style: normal;
  font-weight: bold;
  margin: 0 2px;
}

.primary-btn {
  background: #f56c6c;
  color: white;
  border: none;
  padding: 8px 24px;
  border-radius: 4px;
  font-weight: bold;
}
.suishougou{
  width: 100%;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 10px;
  margin-top: 10px;
  margin-bottom: 10px;
}
.tuijianGood{
  width: 100%;
  height: 450px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #f5f5f5;
}
</style>